package com.znow.admin.system.security.authentication;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author nemo
 * @date 2024/01/08
 */
public class SmsCodeAuthProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsCodeAuthToken smsCodeAuthToken = (SmsCodeAuthToken) authentication;
        String mobile = smsCodeAuthToken.getMobile();

        UserDetails user = userDetailsService.loadUserByUsername(mobile);
        if (user == null) {
            throw new InternalAuthenticationServiceException("用户不存在");
        }
        // 校验验证码是否有效
        SmsCodeAuthToken authenticationResult = new SmsCodeAuthToken(user, user.getAuthorities());
        authenticationResult.setDetails(smsCodeAuthToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return SmsCodeAuthToken.class.isAssignableFrom(aClass);
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}